package service

import (
	"common/biz"
	"context"
	"core/dao"
	"core/repo"
	"framework/msError"
	"regexp"
	"user/pb"
)

type ForgetService struct {
	accountDao *dao.AccountDao
	redisDao   *dao.RedisDao
	pb.UnimplementedForgetPasswordServiceServer
}

func NewForgetService(manager *repo.Manager) *ForgetService {
	return &ForgetService{
		accountDao: dao.NewAccountDao(manager),
		redisDao:   dao.NewRedisDao(manager),
	}
}

func (s *ForgetService) Register(ctx context.Context, req *pb.ForgetPasswordParams) (*pb.ForgetPasswordResponse, error) {
	//查看手机号是否注册
	if req.Account == "" {
		return nil, biz.AccountOrPasswordEmpty
	}
	if req.Password == "" {
		return nil, biz.AccountOrPasswordEmpty
	}
	if req.SmsCode == "" {
		return nil, biz.SmsCodeError
	}
	regex := regexp.MustCompile("[a-zA-Z]")
	passwordCheck := regex.MatchString(req.Password)
	if !passwordCheck {
		return nil, biz.PasswordError
	}
	regex = regexp.MustCompile("[0-9]")
	passwordCheck = regex.MatchString(req.Password)
	if !passwordCheck {
		return nil, biz.PasswordError
	}
	if len(req.Password) < 6 || len(req.Password) > 12 {
		return nil, biz.PasswordError
	}
	user := s.accountDao.UserExists(ctx, req.Account)
	if user == nil || user.ID == 0 {
		return nil, biz.AccountNotExist
	}
	get := s.redisDao.RGet(ctx, req.Account)
	defer s.redisDao.RDel(ctx, req.Account)
	if get != req.SmsCode {
		return nil, biz.SmsCodeError
	}
	err := s.accountDao.ForgetPassword(ctx, user.ID, req.Password)
	if err != nil {
		if err != nil {
			return &pb.ForgetPasswordResponse{}, msError.GrpcError(err)
		}
	}
	return &pb.ForgetPasswordResponse{}, nil
}
